package cn.onlineclass.service;

import cn.onlineclass.dao.CommentMapper;
import cn.onlineclass.entity.OComment;
import cn.onlineclass.util.MybatisUtil;
import com.alibaba.fastjson.JSONPatch;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.onlineclass.vo.AjaxPage;
import cn.onlineclass.vo.AjaxResult;

import java.util.List;

import static com.alibaba.fastjson.JSONPatch.OperationType.add;

public class CommentService {
    private static Logger Log= LoggerFactory.getLogger(CommentService.class);

    public static final CommentService COM=new CommentService();

    public List<OComment> findALL(){
        SqlSession s= MybatisUtil.get();
        try {
            CommentMapper mapper = s.getMapper(CommentMapper.class);
            return mapper.findALL();
        }finally {
            MybatisUtil.close(s);
        }
    }

    //根据id查找单个Student信息
    //根据主键找单个对象的查询方法
    public OComment get(long id){
        SqlSession s =MybatisUtil.get(true);
        try {
            CommentMapper mapper = s.getMapper(CommentMapper.class);
            return mapper.get(id);
        }finally {
            MybatisUtil.close(s);
        }
    }

    public AjaxResult add(OComment c){
        SqlSession s= MybatisUtil.get();
        try {
            CommentMapper mapper = s.getMapper(CommentMapper.class);
            int add = mapper.add(c);
            return AjaxResult.success(JSONPatch.OperationType.add);
        }catch (Exception e){
            Log.error("增加失败",e);
            return AjaxResult.success(0);
        }finally {
            MybatisUtil.close(s);
        }
    }

    public AjaxResult update(OComment c){
        SqlSession s= MybatisUtil.get();
        try {
            CommentMapper mapper = s.getMapper(CommentMapper.class);
            int update = mapper.update(c);
            return AjaxResult.success(update);
        }finally {
            MybatisUtil.close(s);
        }
    }

    public AjaxResult del(long id){
        SqlSession sqlSession= MybatisUtil.get();
        try {
            CommentMapper mapper = sqlSession.getMapper(CommentMapper.class);
            int del =mapper.del(id);
            return AjaxResult.success(del);
        }finally {
            MybatisUtil.close(sqlSession);
        }
    }
    public AjaxPage search(@Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("openid") String openid, @Param("video_id") long video_id){
        SqlSession s= MybatisUtil.get();
        try {
            CommentMapper mapper = s.getMapper(CommentMapper.class);
            List<OComment> search = mapper.search(pageNo, pageSize, openid, video_id);
            int total = mapper.searchTotal(openid, video_id);
            return new AjaxPage(search,total,10,pageNo);
        }finally {
            MybatisUtil.close(s);
        }
    }
}
